import { throttle } from "lodash-es";

const useSearch = defineStore("search", () => {
  const searchEl = useTemplateRef<HTMLDivElement>("searchRef");
  const translateY = ref(0);
  // const lastScrollTop = ref(0);
  const searchHeight = ref(0);
  const router = useRouter();
  const scrollDistance = ref(0);
  const scrollTop = ref(0);
  const lastScrollTop = ref(0);
  const isVisible = ref(true);
  function handleSearch() {
    router.push("/search");
  }
  const handleWinScroll = throttle(() => {
    console.log("🚀 ~ handleWinScroll ~ window.scrollY:", window.scrollY)
    // scrollTop.value = window.scrollY;
    // scrollDistance.value = scrollTop.value - lastScrollTop.value;
    // if (scrollTop.value > lastScrollTop.value) {
    //   translateY.value = translateY.value - scrollDistance.value;
    //   if (translateY.value <= -searchHeight.value) {
    //     translateY.value = -searchHeight.value;
    //   }
    // } else {
    //   translateY.value = translateY.value + Math.abs(scrollDistance.value);
    //   if (translateY.value >= 0) {
    //     translateY.value = 0;
    //   }
    // }
    // lastScrollTop.value = scrollTop.value;
    const scrollTop = window.scrollY;
    const compareLast = scrollTop - lastScrollTop.value;
    if (compareLast > 0) {
      isVisible.value = false;
      // translateY.value = Math.min(translateY.value + compareLast, 48);
    } else {
      isVisible.value = true;
      // translateY.value = Math.max(translateY.value + compareLast, 0);
    }
    lastScrollTop.value = scrollTop;
    console.log("🚀 ~ handleWinScroll ~ lastScrollTop.value:", lastScrollTop.value)
  }, 100);
  onMounted(() => {
    if (searchEl.value) {
      searchHeight.value = searchEl.value.clientHeight;
    }
    // window.addEventListener("scroll", handleWinScroll, {
    //   passive: true,
    // });
  });

  onActivated(() => {
    console.log("🚀 ~ onActivated ~ searchEl.value:", searchEl.value)
    window.addEventListener("scroll", handleWinScroll, {
      passive: true,
    });
  });
  onDeactivated(() => {
    window.removeEventListener("scroll", handleWinScroll);
  });

  return {
    translateY,
    handleSearch,
    scrollDistance,
    scrollTop,
    isVisible,
  };
});
export const useSearchRefs = () => {
  return storeToRefs(useSearch());
};

export default useSearch;
